package com.netease.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Ajax
 */
@WebServlet("/uploadpicture")
public class UploadPicture extends HttpServlet {



	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadPicture() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// String id = request.getParameter("id");
		PrintWriter out = response.getWriter();
		String path = request.getSession().getServletContext().getRealPath("/");
		path = path.substring(0, path.length() - 7);
		path = path + "resources\\static\\picture\\";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
		sfu.setSizeMax(1024 * 1024); // 限制文件大小

		try {
			List<FileItem> fileItems = sfu.parseRequest(request); // 解码请求
																	// 得到所有表单元素
			for (FileItem fi : fileItems) {
				// 有可能是 文件，也可能是普通文字
				if (fi.isFormField()) { // 这个选项是 文字
					System.out.println("表单值为：" + fi.getString());
				} else {
					// 是文件
					String fn = fi.getName();
					System.out.println("文件名是：" + fn); // 文件名
					String [] temp = fn.split("\\.");
					fn = UUID.randomUUID().toString()+"."+temp[1];
					// fn 是可能是这样的 c:\abc\de\tt\fish.jpg
					fi.write(new File(path, fn));
					out.print("/pic/"+fn);
				}
			}
			
			

		} catch (Exception e) {
			e.printStackTrace();
			out.print("false");
		}

	
	out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	 

	}

}
